import React, { useState, useEffect,useRef } from 'react'
import './moduler.css'
import { Button, Input, Select, Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';

import {  message, Popconfirm } from 'antd';
import { getmodluelist } from '../../request/index'



interface Order {
  check: boolean;
  img: string;
  introduction: string;
  producer: string;
  specifications: string;
  status: string;
  price: number;
  num: number;
  shopname: string;
  date: string;

}



const index: React.FC = () => {
  const [modllist, setmodllist] = useState<Order[]>([])//存储订单列表的状态
   const [originalList, setOriginalList] = useState<Order[]>([]);//存储初始订单列表，用于重置筛选
  const [checkedItems, setCheckedItems] = useState<boolean[]>([]);//存储每个订单项的选中状态
  // 存储用于筛选的店铺名和商品名的输入值
  const [shopNameFilter, setShopNameFilter] = useState<string>('');
  const [productNameFilter, setProductNameFilter] = useState<string>('');

  // loading加载
  const [loading,setLoading]=useState(false)//加载状态
  const [page,setPage]=useState(0) //当前页
  const limit=5; // 每次加载的条目数
   const observer = useRef<IntersectionObserver | null>(null);// IntersectionObserver 的引用
     const loadMoreRef = useRef<HTMLDivElement | null>(null); // 加载更多触发器的引用



  // 下拉框的Select
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };

  // 全选框的
  // 处理全选框的变化，更新所有复选框的选中状态
  const handleSelectAllChange = (e: CheckboxProps['onChange']) => {
    const newCheckedState = e.target.checked;
    setCheckedItems(modllist.map(() => newCheckedState));
  };

  // 单个复选框的
  // 处理单个复选框的变化，更新对应项的选中状态
  const handleItemChange = (index: number) => (e: CheckboxProps['onChange']) => {
    const newCheckedItems = [...checkedItems];
    newCheckedItems[index] = e.target.checked;
    setCheckedItems(newCheckedItems);
  };



  // 批量设为好货
  const handleBatchSetGoodGoods = () => {
    const newModllist = modllist.map((item, index) => {
      if (checkedItems[index]) {
        return { ...item, status: '好货' }; // 更新状态为好货
      }
      return item;
    });
     message.success('批量更改完成');
    setmodllist(newModllist); // 更新状态
  };


// 单个设为好货
  const handleSetGoodGoods = (index: number) => {
    const newModllist = [...modllist];
    newModllist[index].status = '好货'; // 更新状态为好货
    setmodllist(newModllist);
    message.success('设为好货完成');
  };

 
    // 设置单个商品为下架
    // 设置单个商品为“已下架”，并将该商品移动到列表末尾
    const setOffline = (index: number) => {
        const newModllist = [...modllist];
        newModllist[index].status = '已下架'; // 更新状态
        const [offlineItem] = newModllist.splice(index, 1); // Remove the item
        newModllist.push(offlineItem); // Push to the end
        setmodllist(newModllist);
        message.success('下架成功');
    };


    // 删除单个商品
    const handleDelete = (index: number) => {
        const newModllist = modllist.filter((_, i) => i !== index); 
        setmodllist(newModllist);
        setCheckedItems(newCheckedItems => newCheckedItems.filter((_, i) => i !== index));
        message.success('删除成功');
    };


// 筛选
// 处理店铺名和商品名的输入变化
const handleShopNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setShopNameFilter(e.target.value);
};

const handleProductNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setProductNameFilter(e.target.value);
};


 const handleFilterOrders = () => {
    // 根据店铺名称和商品名称输入筛选 modllist
    const filteredList = modllist.filter(item =>
      item.shopname.includes(shopNameFilter) &&
      item.introduction.includes(productNameFilter)
    );
    setmodllist(filteredList);
  };


    // 清空筛选条件
    const clearFilters = () => {
        setShopNameFilter('');
        setProductNameFilter('');
        setmodllist(originalList); // Restore the original list
        setCheckedItems(new Array(originalList.length).fill(false)); // Reset checked items
        message.success('筛选条件已清空');
    };

  // 定义获取订单列表的函数
  const fetchmodlueList = async () => {
    try {
      const res = await getmodluelist(); // 调用 API
      console.log('水果订单数据', res.data.modluelist);
     

        setOriginalList(res.data.modluelist); 
         setmodllist(res.data.modluelist.slice(0,limit))// 更新状态
      setCheckedItems(new Array(res.data.modluelist.length).fill(false)); // 初始化选中状态
    } catch (error) {
      console.error('获取水果订单列表时出错:', error);
    }
  };


  // 当用户滚动到底部时加载更多项目
  const loadMoreItems = () => {
    if (loading) return; // 防止多次调用
    setLoading(true);
    const newPage = page + 1;
    const newItems = originalList.slice(newPage * limit, (newPage + 1) * limit);
    if (newItems.length > 0) {
      setmodllist(prev => [...prev, ...newItems]); // 将新项目添加到列表中
      setPage(newPage); // 更新页数
    }
    setLoading(false);
  };


  // 设置 IntersectionObserver 来检测何时加载更多项目
  useEffect(() => {
    if (loadMoreRef.current) {
      observer.current = new IntersectionObserver(entries => {
        if (entries[0].isIntersecting) {
          loadMoreItems(); // 当进入视口时调用加载更多项目
        }
      });

      observer.current.observe(loadMoreRef.current);
    }
    
    return () => {
      if (observer.current && loadMoreRef.current) {
        observer.current.unobserve(loadMoreRef.current); // 清理观察者
      }
    };
  }, [loadMoreRef, loading, page, originalList]);


  useEffect(() => {
    fetchmodlueList();
  }, [])




  return (
    <div className='modluebox'>
      <div className='modluebox_header'>
        <div className='hedtitle'>商品管理</div>
        {/* 1 */}
        <div className='hedone'>
          <p>
            商品大类:
            <Select
              defaultValue="请选择大类"
              style={{ width: 284 }}
              onChange={handleChange}
              options={[
                { value: '请选择大类', label: '请选择大类' },
                { value: '水果', label: '水果' },
                { value: '生活', label: '生活' },
                { value: '电器', label: '电器' },
                { value: '品牌', label: '品牌' },
                { value: '厨房', label: '厨房' },
              ]}
            />
          </p>
          <p>
            商品小类：
            <Select
              defaultValue="请选择小类"
              style={{ width: 284 }}
              onChange={handleChange}
              options={[
                { value: '请选择小类', label: '请选择小类' },
                { value: '苹果', label: '苹果' },
                { value: '香蕉', label: '香蕉' },
                { value: '橘子', label: '橘子' },
                { value: '火龙果', label: '火龙果' },
                { value: '柚子', label: '柚子' },
              ]}
            />
          </p>
          <p>
            曝光类型：
            <Select
              defaultValue="全部"
              style={{ width: 120 }}
              onChange={handleChange}
              options={[
                { value: '全部', label: '全部' },
                { value: '苹果', label: '苹果' },
                { value: '香蕉', label: '香蕉' },
                { value: '橘子', label: '橘子' },
                { value: '火龙果', label: '火龙果' },
                { value: '柚子', label: '柚子' },
              ]}
            />
          </p>

        </div>
        {/* 2 */}
        <div className='hedtwo'>
          <p>
            好货设置：
            <Select
              defaultValue="好货"
              style={{ width: 120 }}
              onChange={handleChange}
              options={[
                { value: '好货', label: '好货' },
                { value: '常货', label: '常货' },
                { value: '干货', label: '干货' },
                { value: '实货', label: '橘子' },
                { value: '赔钱货', label: '赔钱货' },
                { value: '运货', label: '运货' },
              ]}
            />
            &emsp;
            <Select
              defaultValue="所有分组"
              style={{ width: 120 }}
              onChange={handleChange}
              options={[
                { value: '所有分组', label: '所有分组' },
                { value: '常货', label: '常货' },
                { value: '干货', label: '干货' },
                { value: '实货', label: '橘子' },
                { value: '赔钱货', label: '赔钱货' },
                { value: '运货', label: '运货' },
              ]}
            />
          </p>
          <p>退款类型：
            <Select
              defaultValue="请选择退款类型"
              style={{ width: 284 }}
              onChange={handleChange}
              options={[
                { value: '请选择退款类型', label: '请选择退款类型' },
                { value: '普通退款', label: '普通退款' },
                { value: '快速退款', label: '快速退款' },

              ]}
            />
          </p>
        </div>
        {/* 3 */}
        <div className='hedthree'>
          <p>店铺名称:<Input placeholder="请输入店铺名称"   value={shopNameFilter} onChange={handleShopNameChange} style={{ width: '250px' }} /></p>
          <p>商品名称:<Input placeholder="请输入商品名称"  value={productNameFilter} onChange={handleProductNameChange} style={{ width: '250px' }} /></p>
        </div>
        {/* 4 */}
        <div className='hedfour'>
          <Button type="primary" onClick={handleFilterOrders}>筛选订单</Button>
          <Button onClick={clearFilters}>清空筛选条件</Button>
          <Button>设置模板</Button>
        </div>

      </div>

      <div className='modluebox_tabs'>
        <div className='tabs_hed'>
          <Checkbox
            onChange={handleSelectAllChange}
            checked={checkedItems.length > 0 && checkedItems.every(checked => checked)} style={{ marginLeft: '10px' }}>全选</Checkbox>
          <Button style={{ marginLeft: '40px' }} onClick={handleBatchSetGoodGoods}>批量设为好货</Button>
        </div>

        {/* 表格标题部分 */}
        <div className='tabs_title'>

          <p className='tone'>&emsp;&emsp;商品描述</p>
          <p className='ttwo'>价格</p>
          <p className='tthree'>销量</p>
          <p className='tfour'>店铺</p>
          <p className='tfive'>创建时间</p>
          <p className='tsix'>操作</p>
        </div>

        {/* 表格内容部分 */}
        {
          modllist && modllist.map((item, index) => {
            return (
              <div key={index} className='tabs_content'>
                <div className='contone'>
                  <Checkbox onChange={handleItemChange(index)}
                    checked={checkedItems[index]} style={{ marginLeft: '10px' }}></Checkbox>
                  <img src={item.img} alt="" style={{ marginLeft: '20px' }} />

                  <div style={{ marginLeft: '50px' }}>
                    <p style={{ width: '270px', fontSize: '16px' }}>{item.introduction}</p>
                    <p style={{ width: '300px', color: '#81858c', marginTop: '10px' }}>产地:<span>{item.producer}</span>&emsp; 规格:<span>{item.specifications}</span>&emsp;特性:其它</p>

                    <p style={{ color: 'red', fontSize: '16px', marginTop: '20px' }}>{item.status}</p>
                  </div>
                </div>

                <div className='conttwo'>
                  <p>￥<span>{item.price}</span></p>
                </div>

                <div className='contthree'>
                  <p>{item.num}</p>
                </div>

                <div className='contfour'>
                  <p>{item.shopname}</p>
                </div>

                <div className='contfive'>
                  <p>{item.date}</p>
                </div>

                <div className='contsix'>
                  <p onClick={() => handleSetGoodGoods(index)}>设为好货</p>
                  <p onClick={() => setOffline(index)}>下架</p>
                    <Popconfirm
    title="删除确认"
    description="你确定要删除吗？"
    onConfirm={() => handleDelete(index)}
    okText="是"
    cancelText="否"
  >
                  <p>删除</p>
                  </Popconfirm>
                </div>
              </div>
            )
          })
        }

             {/* 加载更多触发器 */}
        <div ref={loadMoreRef} style={{ height: '20px' }} />
     

      </div>


    </div>
  )
}

export default index
